/**
 * Created by apple on 2017/7/5.
 */


var SrvLink = module.exports;
var async = require('async');
var DBFactory = require('../db/mysql_db.js');
var globalVar = require('../global_var');
var PostHelper = require('../util/postHelper');
var then = require('thenjs');

/*
 //如果是扣除积分、押金类型时，字段存放有所区别
 var vipLogInfo = {

 seller_account: 'srv',
 client_account: userVipInfo.account,
 vip_sid: data.vip_sid,                                     //用来存放vip_sid
 vip_name: data.vipName ? data.vipName : 'srv',    //用来存放商品短标题
 original_vip_name: data.vipName ? data.vipName : 'srv',    //变动的话，用来存记录类型；购买的话，用来存先前买的vip的item名。两者根据cost区分
 vip_type: userVipInfo.vip_type,
 lvl: data.point,
 duration: '0',
 cost: 0,
 exInfo: data.exInfo,
 comment: data.comment,
 price: 0,
 num: 1,
 app_sid: data.appSid,
 original_lvl: userVipInfo.lvl,
 sign: 1
 };
 */
//uid,sign(0：增加，1减少),exInfo(选),comment(选),
SrvLink.publishGoodsByPD = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },

                //查询用户积分和信用积分
                function (callback) {
                    var diffPoint;
                    connection.query('SELECT vip_type,update_time,vip_sid,lvl,account FROM user_vip WHERE uid = ? AND app_sid = ?' +
                        ' AND vip_sid in ("creditLvl","moneyPoint")', [data.uid, data.app_key], function (err, result) {
                        if (result && result.length == 2) {
                            var mp = {};
                            var diffDay;
                            var diffPool;
                            result.forEach(function (vip) {
                                //信用积分
                                if (vip.vip_sid == 'creditLvl') {
                                    var diffLvl = parseInt(globalVar.config[data.app_key + '_uploadGoodLvl'].value) - vip.lvl;
                                    //如果信用等级<100,开启惩罚机制
                                    if (diffLvl > 0) {
                                        var now = new Date();
                                        //计算相差几天
                                        var dayNum = Math.floor((now.getTime() - vip.update_time.getTime()) / (24 * 3600 * 1000));
                                        var okTime = vip.update_time.getTime() + diffLvl*(24*3600*1000);

                                        diffPool = getDatePoor(okTime,now.getTime());
                                        diffDay = diffLvl - dayNum;
                                    }
                                } else if (vip.vip_sid == 'moneyPoint') {
                                    mp = vip;
                                }
                            });
                            //信用积分
                            if (diffDay > 0) {
                                // callback('当前信用等级不够，还有' + diffDay + '天，才能提交商品');
                                callback('当前信用等级不够，还有' + diffPool + '，才能提交商品');
                                return;
                            }
                            //用户积分
                            if (data.isNotFirstPublish == 1) {
                                diffPoint = parseInt(globalVar.config[data.app_key + '_reUploadGoodCost'].value) - mp.lvl;
                            } else {
                                diffPoint = parseInt(globalVar.config[data.app_key + '_uploadGoodCost'].value) - mp.lvl;
                            }
                            if (diffPoint > 0) {
                                callback('当前只剩' + mp.lvl + '个积分，还需' + diffPoint + '个积分才能上传商品');
                                return;
                            }
                            mp.diffPoint = -diffPoint;
                            callback(null, mp);
                            return;
                        } else {
                            callback('用户还未通过认证,无法上传商品');
                            return;
                        }
                    });
                },

                // 查询项目上限
                // function (userVipInfo, callback) {
                //     if (!userVipInfo) {
                //         callback('请先购买');
                //         return;
                //     }
                //     connection.query('SELECT top_lvl FROM app_vip WHERE app_sid = ? AND sid = ? ', [data.appSid, data.vipSid], function (err, result) {
                //         var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                //         if (!vipInfo) {
                //             callback('查无此权限');
                //             return;
                //         }
                //
                //         if (userVipInfo.vip_type != 1 && userVipInfo.vip_type != 2) {//只修改数值类
                //             callback('不可扣除');
                //             return;
                //         }
                //
                //         if (data.sign == 0) {//增加
                //
                //             if ((data.point + userVipInfo.lvl) > vipInfo.top_lvl) {
                //                 callback('超过上限');
                //                 return;
                //             }
                //
                //         } else {
                //
                //             if (userVipInfo.lvl < data.point) {
                //                 callback('余量不足');
                //                 return;
                //             }
                //
                //         }
                //         callback(null, userVipInfo);
                //     });
                // },

                //更改 财富积分
                function (userVip, callback) {
                    if (userVip.diffPoint < 0) {
                        callback('用户没有积分可扣');
                        return;
                    }
                    userVip.update_time = new Date();
                    connection.query('UPDATE user_vip SET lvl = ?,update_time = ? WHERE uid = ? AND app_sid = ? AND vip_sid = "moneyPoint"', [userVip.diffPoint, userVip.update_time, data.uid, data.app_key], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, userVip);
                            return;
                        }
                        callback('扣除失败');
                        console.log('更改user_vip表失败')
                        return;
                    });
                },

                //记录扣除记录
                function (userVip, callback) {
                    if (!userVip) {
                        callback('扣除失败');
                        return;
                    }
                    var vipLogInfo = {

                        seller_account: 'srv',
                        client_account: userVip.account,
                        vip_name: data.goodShortTitle ? data.goodShortTitle : 'srv', //vip_type为1时，这项是商品短标题
                        vip_type: userVip.vip_type,
                        lvl: userVip.lvl - userVip.diffPoint,//变动多少
                        duration: '0',
                        cost: 0,
                        exInfo: data.pictUrl,
                        comment: data.isNotFirstPublish == '0' ? globalVar.config[data.app_key + '_uploadGoodCost'].comment + globalVar.config[data.app_key + '_uploadGoodCost'].value : globalVar.config[data.app_key + '_uploadGoodCost'].comment + globalVar.config[data.app_key + '_uploadGoodCost'].value,
                        original_vip_name: data.isNotFirstPublish == 0 ? '发布扣除积分' : '编辑扣除积分',
                        price: 0,
                        num: 1,
                        app_sid: data.app_key,
                        vip_sid: userVip.vip_sid,
                        created_date: userVip.update_time,
                        original_lvl: userVip.lvl,
                        sign: 1//sign(0:增加 1减少)
                    };
                    connection.query('INSERT INTO vip_log SET ? ', [vipLogInfo], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败');
                            console.log('添加vip_log表失败')
                            return;
                        }
                        // var newLvl = vipLogInfo.original_lvl - vipLogInfo.lvl;
                        callback(null, '操作成功');
                    });
                }
            ],
            function (err, res) {
                if (err) {
                    connection.rollback(function () {
                        connection.release();
                        cb(err);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, res);
                        }
                    });
                }
            }
        );
    });
}

function viplogsColumnNames() {
    return "`seller_account`,`client_account`,`vip_name`,`vip_type`,`lvl`," +
        "`duration`,`cost`,`exInfo`,`comment`,`original_client`,`original_vip_name`,`price`,`num`," +
        "`app_sid`,`vip_sid`,`created_date`,`original_lvl`,`sign`";
}

function getviplogsInfo(userInfos, data) {
    var viplogs = [];
    for (var i = 0; i < userInfos.length; i++) {
        var theData = userInfos[i];
        viplogs.push(viplogsInfoColumn(theData, data));
    }
    return viplogs;
}

function getviplogsInfo1(userInfos, data) {
    var viplogs = [];
    for (var i = 0; i < userInfos.length; i++) {
        var theData = userInfos[i];
        viplogs.push(viplogsInfoColumn1(theData, data));
    }
    return viplogs;
}

function viplogsInfoColumn(theData, data) {
    var viplogs = [];
    viplogs.push('srv');
    viplogs.push(theData.account);
    viplogs.push(theData.goodShortTitle);
    viplogs.push(theData.vip_type);
    if(data.isScore){
        viplogs.push(globalVar.config[data.app_sid + '_uploadGoodCostFalse'].value);
    }else {
        viplogs.push(Math.abs(theData.nowLvl - theData.lvl));
    }
    viplogs.push('0');
    viplogs.push(0);
    viplogs.push(theData.pictUrl);
    if(data.isScore){
        viplogs.push(globalVar.config[data.app_sid + '_uploadGoodCostFalse'].comment + globalVar.config[data.app_sid + '_uploadGoodCostFalse'].value);
    }else {
        viplogs.push(data.sign == '0' ? globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].comment + globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].value : globalVar.config[data.app_sid + '_uploadGoodLvlFalse'].comment + theData.diffLvl);
    }
    viplogs.push(theData.id);
    if(data.isScore){
        viplogs.push('拒绝返还积分');
    }else {
        viplogs.push(data.sign == 0 ? '通过奖励积分' : '拒绝扣除积分');
    }
    viplogs.push(0);
    viplogs.push(1);
    viplogs.push(data.app_sid);
    if(data.isScore){
        viplogs.push("moneyPoint");
    }else {
        viplogs.push(data.vip_sid);
    }
    viplogs.push(data.vfy_date);
    if(data.isScore){
        viplogs.push(theData.score);
    }else {
        viplogs.push(theData.lvl);
    }
    if(data.isScore){
        viplogs.push(0);
    }else {
        viplogs.push(data.sign);
    }
    return viplogs;
}

function viplogsInfoColumn1(theData, data) {
    var viplogs = [];
    viplogs.push('srv');
    viplogs.push(theData.account);
    viplogs.push(data.goods[theData.uid].goodShortTitle);
    viplogs.push(theData.vip_type);
    if(data.isScore){
        viplogs.push(globalVar.config[data.app_sid + '_uploadGoodCostFalse'].value);
    }else {
        viplogs.push(Math.abs(theData.nowLvl - theData.lvl));
    }
    viplogs.push('0');
    viplogs.push(0);
    viplogs.push(data.goods[theData.uid].pictUrl);
    if(data.isScore){
        viplogs.push(globalVar.config[data.app_sid + '_uploadGoodCostFalse'].comment + globalVar.config[data.app_sid + '_uploadGoodCostFalse'].value);
    }else {
        viplogs.push(data.sign == '0' ? globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].comment + globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].value : globalVar.config[data.app_sid + '_uploadGoodLvlFalse'].comment + data.goods[theData.uid].diffLvl);
    }
    viplogs.push(data.goods[theData.uid].id);
    if(data.isScore){
        viplogs.push('拒绝返还积分');
    }else {
        viplogs.push(data.sign == 0 ? '通过奖励积分' : '拒绝扣除积分');
    }
    viplogs.push(0);
    viplogs.push(1);
    viplogs.push(data.app_sid);
    if(data.isScore){
        viplogs.push("moneyPoint");
    }else {
        viplogs.push(data.vip_sid);
    }
    viplogs.push(data.vfy_date);
    if(data.isScore){
        viplogs.push(theData.score);
    }else {
        viplogs.push(theData.lvl);
    }
    if(data.isScore){
        viplogs.push(0);
    }else {
        viplogs.push(data.sign);
    }
    return viplogs;
}


//data: 1、uids表用户列表（数组）2、app_sid 3、vip_vip
SrvLink.alterLvlByAuditGoods = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },
                //增加信用积分
                function (callback) {
                    if (data.passEasyGoods) {
                        var passParam = {};
                        passParam.goods = JSON.parse(data.passEasyGoods);
                        if (data.handleGoods) {
                            passParam.handleGoods = JSON.parse(data.handleGoods);
                        }
                        passParam.blpd_APP_key = data.blpd_APP_key;
                        passParam.blpd_APP_secret = data.blpd_APP_secret;
                        passParam.TaoSrvHost = data.TaoSrvHost;
                        passParam.sign = 0;//0表增加
                        passParam.vfy_date = data.vfy_date;
                        passParam.vip_sid = data.vip_sid;
                        passParam.app_sid = data.app_sid;
                        SrvLink.alterLvlByPd(passParam, function (e, result) {
                            if (e) {
                                callback(e);
                                console.log(e);
                                return;
                            }
                            callback(null, "操作成功");
                        });
                    } else {
                        callback(null, '操作成功');
                    }
                },
                //减少信用积分
                function (r, callback) {
                    if (data.refuseEasyGoods) {
                        var refuseParam = {};
                        refuseParam.goods = JSON.parse(data.refuseEasyGoods);
                        refuseParam.sign = 1;//1表减少
                        refuseParam.vip_sid = data.vip_sid;
                        refuseParam.vfy_date = data.vfy_date;
                        refuseParam.app_sid = data.app_sid;
                        SrvLink.alterLvlByPd(refuseParam, function (e, result) {
                            if (e) {
                                callback(e);
                                console.log(e);
                                return;
                            }
                            callback(null, "操作成功");
                        });
                    } else {
                        callback(null, "操作成功");
                    }
                },
            ],
            function (err, res) {
                if (err) {
                    connection.rollback(function () {
                        connection.release();
                        cb(err);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, res);

                        }
                    });
                }
            }
        );
    });
}

/**
 * [跑单连接]管理员已拒绝，又给商品通过（ 1、返还积分（user_vip表+1信用积分）2、修改vip_log记录 3、上传到奔流）
 * @param data
 * @param cb
 */
SrvLink.alterLvlByRePassGood = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        var curLvl;
        var addLvl;
        var topLvl;
        var oldLvl;
        data.rePassGood = JSON.parse(data.rePassGood);
        async.waterfall([
                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },
                //查看被扣除的记录
                function (callback) {
                    // var sql = 'select a.*,b.account from vip_log a left join users b on a.client_account = b.account where a.original_client = ? and a.sign = 1 and a.app_sid = "paodan" and a.vip_sid = "creditLvl" and a.created_date = ?'; //and b.uid = ?';
                    // var sql = 'select * from vip_log where original_client = ? and sign = 1 and app_sid = "paodan" and vip_sid = "creditLvl" and created_date = ?'; //and b.uid = ?';
                    var sql = 'select a.*,b.top_lvl from vip_log a left join app_vip b on a.app_sid = b.app_sid and a.vip_sid = b.sid where a.original_client = ?  and a.created_date = ? and a.app_sid = "paodan" and a.vip_sid = "creditLvl" ';
                    var sqlValue = [data.rePassGood.id,simpleDateFormat(data.rePassGood.vfy_date)];
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.length == 1) {
                            topLvl = result[0].top_lvl;
                            addLvl = parseInt(globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].value) + result[0].lvl;//查询扣除的积分
                            callback(null, result[0]);
                        } else {
                            callback("找不到被扣的记录");
                        }
                    })
                },
                function (log,callback) {
                    var sql = 'select lvl from user_vip WHERE uid = ? AND app_sid = "paodan" AND vip_sid = "creditLvl"';
                    var sqlValue = [data.rePassGood.uid_own];
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.length == 1) {
                            oldLvl = result[0].lvl;
                            curLvl = result[0].lvl + addLvl;
                            if(curLvl > topLvl){
                                curLvl = topLvl;
                                addLvl = curLvl-oldLvl;
                            }
                            callback(null, log);
                        } else {
                            callback("请确定该用户是否有信用积分权限");
                        }
                    })
                },

                //user_vip：返还积分
                function (log, callback) {
                    var sql = 'UPDATE user_vip SET lvl = ?,update_time=? WHERE uid = ? AND app_sid = "paodan" AND vip_sid = "creditLvl"';
                    var sqlValue = [curLvl,data.vfy_date, data.rePassGood.uid_own];
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, log);
                        }
                    })
                },
                //vip_log：修改记录
                function (log, callback) {

                    var vipLogInfo = {
                        seller_account: 'srv',
                        client_account: log.client_account,
                        vip_name: data.rePassGood.goodShortTitle,
                        vip_type: log.vip_type,
                        lvl: addLvl,//变动多少
                        duration: '0',
                        cost: 0,
                        exInfo: data.rePassGood.pictUrl,
                        comment: globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].comment + addLvl,
                        original_client: data.rePassGood.id,
                        original_vip_name: "通过奖励积分",
                        price: 0,
                        num: 1,
                        app_sid: log.app_sid,
                        vip_sid: log.vip_sid,
                        created_date: data.vfy_date,
                        original_lvl: oldLvl,
                        sign: 0//sign(0:增加 1:减少)
                    };

                    connection.query('INSERT INTO vip_log SET ? ', [vipLogInfo], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows > 0) {
                            callback(null, log);
                        } else {
                            console.log("添加vip_log失败");
                            callback("添加vip_log失败");
                        }
                    })
                },
                //上传到奔流
                function (log, callback) {
                    if (data.isShelf == 1) {
                        var par = getParWithSign(data.blpd_APP_key, data.blpd_APP_secret);
                        var goods = [];
                        goods.push(data.rePassGood);
                        par.goods = JSON.stringify(goods);
                        // par.token = data.token;
                        PostHelper.jsonPost(data.TaoSrvHost, '/goods/addGoodsFromPDS', 3000, par, function (err, data) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            callback(null, "操作成功");
                        });
                    } else {
                        callback(null, '操作成功');
                    }
                },
            ],
            function (err, res) {
                if (err) {
                    connection.rollback(function () {
                        connection.release();
                        cb(err);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, res);
                        }
                    });
                }
            }
        );
    });
}

//data: 1、uids表用户列表（数组）2、app_sid 3、vip_vip
SrvLink.alterLvlByPd = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        var ifSubLvl;
        var isPassByBenliu = true;
        var refuseReason;
        var uids = {};
        var uidList = [];
        async.waterfall([
                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },
                //查询项目上限
                function (callback) {
                    var sql = 'SELECT * FROM app_vip WHERE app_sid = ? AND sid = ?';
                    var sqlValue = [data.app_sid];
                    if (data.sign == 1) {
                        sqlValue.push("moneyPoint");
                    } else {
                        sqlValue.push(data.vip_sid);
                    }
                    connection.query(sql, sqlValue, function (err, result) {
                        var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                        if (!vipInfo) {
                            callback('查无此权限');
                            return;
                        }
                        if (vipInfo.type != 1 && vipInfo.type != 2) {//只修改数值类
                            callback('不可扣除');
                            return;
                        }
                        callback(null, vipInfo.top_lvl);
                    });
                },
                //查询用户积分/信用等级/押金
                function (level_lvl, callback) {
                    // data.uids = [];
                    // for (var uid in data.goods) {
                    //     data.uids.push(parseInt(uid));
                    // }
                    var vipInfos = [];
                    then.eachSeries(data.goods, function (defer, item) {
                        var sql = '';
                        if (data.sign == 0) {
                            sql += 'SELECT vip_type,update_time,vip_sid,lvl,account,uid FROM user_vip WHERE uid = ? AND app_sid = ? AND vip_sid = ?';
                        } else {
                            sql += 'SELECT a.*,b.lvl score from (SELECT vip_type,update_time,lvl,account,uid FROM user_vip WHERE uid = ? AND app_sid = ? AND vip_sid = ?) a left join user_vip b on a.uid = b.uid where b.vip_sid = "moneyPoint"';
                        }
                        console.log(sql);
                        connection.query(sql, [item.uid, data.app_sid, data.vip_sid],
                            function (err, result) {
                                if (err) {
                                    callback(err);
                                    console.log(err);
                                    return;
                                }
                                if (result && result[0]) {
                                    var vipInfo = {};
                                    //0表增加，1表减少
                                    vipInfo = result[0];
                                    if (data.sign == 0) {
                                        if(uids[item.uid]){
                                            vipInfo.lvl = uids[item.uid].curLvl;
                                            vipInfo.nowLvl = uids[item.uid].curLvl - item.diffLvl;
                                        }else {
                                            uids[item.uid] = {};
                                            vipInfo.nowLvl = result[0].lvl + parseInt(globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].value);
                                        }
                                        if (vipInfo.nowLvl > level_lvl) {
                                            vipInfo.nowLvl = level_lvl;
                                        }
                                        uids[item.uid].curLvl = vipInfo.nowLvl;
                                        // ifSubLvl = o.lvl - parseInt(globalVar.config[data.app_sid + '_uploadGoodLvlFalse'].value);
                                    } else {
                                        if(uids[item.uid]){
                                            vipInfo.lvl = uids[item.uid].curLvl;
                                            vipInfo.score = uids[item.uid].curScore;
                                            vipInfo.nowLvl = uids[item.uid].curLvl - item.diffLvl;
                                            vipInfo.nowScore = uids[item.uid].curScore + parseInt(globalVar.config[data.app_sid + '_uploadGoodCostFalse'].value);
                                        }else {
                                            uids[item.uid] = {};
                                            vipInfo.nowLvl = result[0].lvl - item.diffLvl;
                                            vipInfo.nowScore = result[0].score + parseInt(globalVar.config[data.app_sid + '_uploadGoodCostFalse'].value);
                                        }
                                        // vipInfo.nowLvl = o.lvl - parseInt(globalVar.config[data.app_sid + '_uploadGoodLvlFalse'].value);
                                        if (vipInfo.nowLvl <= 0) {
                                            vipInfo.nowLvl = 0;
                                        }
                                        if (vipInfo.nowScore > level_lvl) {
                                            vipInfo.nowScore = level_lvl;
                                        }
                                        uids[item.uid].curLvl = vipInfo.nowLvl;
                                        uids[item.uid].curScore = vipInfo.nowScore;
                                    }
                                    vipInfo.id = item.id;
                                    vipInfo.goodShortTitle = item.goodShortTitle;
                                    vipInfo.pictUrl = item.pictUrl;
                                    vipInfo.diffLvl = item.diffLvl;
                                    vipInfos.push(vipInfo);
                                    defer(null, item);
                                } else {
                                    callback('有用户还未通过认证,其商品无效处理');
                                    return;
                                }
                            });

                    }).then(function (defer, result) {
                        callback(null, vipInfos);
                    }).fail(function (defer, err) {
                        console.log(err);
                        callback(err);
                    })

                },
                //上传到奔流
                function (vipInfos, callback) {
                    if (data.sign == 0 && data.handleGoods) {
                        //上传到奔流
                        var par = getParWithSign(data.blpd_APP_key, data.blpd_APP_secret);
                        par.goods = JSON.stringify(data.handleGoods);
                        // par.token = data.token;
                        PostHelper.jsonPost(data.TaoSrvHost, '/goods/addGoodsFromPDS', 3000, par, function (err, data) {
                            if (err) {
                                //上架失败，只有一条记录,直接全给他操作失败，让他再选择操作
                                // isPassByBenliu = false;
                                // data.sign = 1;
                                // refuseReason = err;
                                // vipInfos[0].nowLvl = ifSubLvl;
                                callback(err);
                                return;
                            }
                            callback(null, vipInfos);
                        });
                    } else {
                        callback(null, vipInfos);
                    }
                },
                //更改 信用积分
                function (vipInfos, callback) {
                    var sql = '';
                    var sqlValue = [];
                    sql = 'UPDATE user_vip'
                        + ' set update_time = ?'
                        + ',lvl = CASE uid';
                    sqlValue.push(data.vfy_date);
                    for(var uid in uids){
                        uidList.push(uid);
                        sql += ' WHEN ' + uid + ' THEN ' + uids[uid].curLvl;
                    }
                    // vipInfos.forEach(function (vip) {
                    //     sql += ' WHEN ' + vip.uid + ' THEN ' + vip.nowLvl;
                    // })
                    sql += ' END';
                    sql += ' where uid in (?) and app_sid = ? and vip_sid = ?';
                    sqlValue.push(uidList);
                    sqlValue.push(data.app_sid);
                    sqlValue.push(data.vip_sid);
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows == uidList.length) {
                            callback(null, vipInfos);
                            return;
                        }
                        callback('修改user_vip表失败');
                        console.log('更改user_vip表失败');
                        return;
                    });
                },
                //记录扣除记录
                function (userVips, callback) {
                    // var vips = getviplogsInfo(userVips, data);
                    var vips = getviplogsInfo(userVips, data);
                    connection.query('INSERT INTO vip_log (' + viplogsColumnNames() + ') values ? ', [vips], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败');
                            console.log('添加vip_log表失败');
                            return;
                        }
                        callback(null, userVips);
                    });
                },
                //更改 财富积分
                function (vipInfos, callback) {
                    if(data.sign == 0){
                        callback(null,vipInfos);
                        return;
                    }
                    var sql = '';
                    var sqlValue = [];
                    sql = 'UPDATE user_vip'
                        + ' set update_time = ?'
                        + ',lvl = CASE uid';
                    sqlValue.push(data.vfy_date);
                    for(var uid in uids) {
                        sql += ' WHEN ' + uid + ' THEN ' + uids[uid].curScore;
                    }
                    sql += ' END';
                    sql += ' where uid in (?) and app_sid = ? and vip_sid = ?';
                    sqlValue.push(uidList);
                    sqlValue.push(data.app_sid);
                    sqlValue.push("moneyPoint");
                    connection.query(sql, sqlValue, function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows == uidList.length) {
                            callback(null, vipInfos);
                            return;
                        }
                        callback('修改user_vip表失败');
                        console.log('更改user_vip表的财富积分失败');
                        return;
                    });
                },
                //记录返还记录
                function (userVips, callback) {
                    if(data.sign == 0){
                        callback(null,userVips);
                        return;
                    }
                    data.isScore = 1;
                    var vips = getviplogsInfo(userVips, data);
                    connection.query('INSERT INTO vip_log (' + viplogsColumnNames() + ') values ? ', [vips], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败');
                            console.log('添加vip_log表失败');
                            return;
                        }
                        callback(null, userVips);
                    });
                }
            ],
            function (err, res) {
                if (err) {
                    connection.rollback(function () {
                        connection.release();
                        cb(err);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, res);
                        }
                    });
                }
            }
        );
    });
}

// 已弃用（不继续维护了）
//data: 1、uids表用户列表（数组）2、app_sid 3、vip_vip
SrvLink.alterLvl = function (data, cb) {
    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([
                function (callback) {
                    connection.beginTransaction(function (err) {
                        callback(err);
                    });
                },
                //查询项目上限
                function (callback) {
                    if (data.sign == 1) {
                        callback(null, 0);
                    } else {
                        connection.query('SELECT * FROM app_vip WHERE app_sid = ? AND sid = ? ', [data.app_sid, data.vip_sid], function (err, result) {
                            var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                            if (!vipInfo) {
                                callback('查无此权限');
                                return;
                            }
                            if (vipInfo.type != 1 && vipInfo.type != 2) {//只修改数值类
                                callback('不可扣除');
                                return;
                            }
                            callback(null, vipInfo.top_lvl);
                        });
                    }
                },
                //查询用户积分/信用等级/押金
                function (level_lvl, callback) {
                    data.uids = [];
                    for (var uid in data.goods) {
                        data.uids.push(parseInt(uid));
                    }
                    connection.query('SELECT vip_type,update_time,vip_sid,lvl,account,uid FROM user_vip WHERE' +
                        ' uid in (?) AND app_sid = ? AND vip_sid = ?', [data.uids, data.app_sid, data.vip_sid],
                        function (err, result) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            if (result && result.length == data.uids.length) {
                                var vipInfos = [];
                                result.forEach(function (o) {
                                    var vipInfo = {};
                                    //0表增加，1表减少
                                    vipInfo = o;
                                    if (data.sign == 0) {
                                        vipInfo.nowLvl = o.lvl + parseInt(globalVar.config[data.app_sid + '_uploadGoodLvlSuccess'].value);
                                        if (vipInfo.nowLvl > level_lvl) {
                                            vipInfo.nowLvl = level_lvl;
                                        }
                                    } else {
                                        // vipInfo.nowLvl = o.lvl - parseInt(globalVar.config[data.app_sid + '_uploadGoodLvlFalse'].value);
                                        vipInfo.nowLvl = o.lvl - data.goods[o.uid].diffLvl;
                                        if (vipInfo.nowLvl <= 0) {
                                            vipInfo.nowLvl = 0;
                                        }
                                    }
                                    vipInfos.push(vipInfo);
                                })
                                callback(null, vipInfos);
                            } else {
                                callback('有用户还未通过认证,其商品无效处理');
                                return;
                            }
                        });
                },
                //更改 财富积分
                function (vipInfos, callback) {
                    //更改状态
                    var sql = 'UPDATE user_vip'
                        + ' set update_time = curTime()'
                        + ',lvl = CASE uid';
                    vipInfos.forEach(function (vip) {
                        sql += ' WHEN ' + vip.uid + ' THEN ' + vip.nowLvl;
                    })
                    sql += ' END';
                    sql += ' where uid in (?) and app_sid = ? and vip_sid = ?';
                    connection.query(sql,
                        [data.uids, data.app_sid, data.vip_sid], function (err, result) {
                            if (err) {
                                console.log(err);
                                callback(err);
                                return;
                            }
                            if (result.affectedRows == data.uids.length) {
                                callback(null, vipInfos);
                                return;
                            }
                            callback('修改user_vip表失败');
                            console.log('更改user_vip表失败');
                            return;
                        });
                },
                //记录扣除记录
                function (userVips, callback) {
                    var vips = getviplogsInfo1(userVips, data);
                    connection.query('INSERT INTO vip_log (' + viplogsColumnNames() + ') values ? ', [vips], function (err, result) {
                        if (err) {
                            console.log(err);
                            callback(err);
                            return;
                        }
                        if (result.affectedRows <= 0) {
                            callback('操作失败');
                            console.log('添加vip_log表失败')
                            return;
                        }
                        callback(null, '操作成功');
                    });
                }
                //管理员给的，还要再记录admin_log吗? 目前先不记
            ],
            function (err, res) {
                if (err) {
                    connection.rollback(function () {
                        connection.release();
                        cb(err);
                    });
                } else {
                    connection.commit(function (e) {
                        if (e) {
                            connection.rollback(function () {
                                connection.release();
                                cb(e);
                            });
                        } else {
                            connection.release();
                            cb(null, res);
                        }
                    });
                }
            }
        );
    });
}

/*
 //如果是扣除积分、押金类型时，字段存放有所区别
 var vipLogInfo = {

 seller_account: 'srv',
 client_account: userVipInfo.account,
 vip_name: data.vipSid,                                     //用来存放vip_sid
 original_vip_name: data.vipName ? data.vipName : 'srv',    //用来存放商品短标题
 vip_type: userVipInfo.vip_type,
 lvl: data.point,
 duration: '0',
 cost: 0,
 exInfo: data.exInfo,
 comment: data.comment,
 price: 0,
 num: 1,
 app_sid: data.appSid,
 original_lvl: userVipInfo.lvl,
 sign: 1
 };

 */
//uid，app_sid, vip_sid, point,sign(0：增加，1减少),exInfo(选),comment(选)
SrvLink.alterPoints = function (data, cb) {

    DBFactory.getConnection(function (error, connection) {
        if (error) {
            cb(error);
            return;
        }
        async.waterfall([

            function (callback) {
                connection.beginTransaction(function (err) {
                    callback(err);
                });
            },

            //查询用户积分／押金／信用积分
            function (callback) {
                connection.query('SELECT vip_type,lvl,account FROM user_vip WHERE uid = ? AND app_sid = ? AND vip_sid = ? ', [data.uid, data.appSid, data.vipSid], function (err, result) {
                    var userVipInfo = (result && result.length > 0) ? result[0] : undefined;
                    callback(null, userVipInfo);
                });
            },

            //查询项目上限
            function (userVipInfo, callback) {
                if (!userVipInfo) {
                    callback('请先购买');
                    return;
                }
                connection.query('SELECT top_lvl FROM app_vip WHERE app_sid = ? AND sid = ? ', [data.appSid, data.vipSid], function (err, result) {
                    var vipInfo = (result && result.length > 0) ? result[0] : undefined;
                    if (!vipInfo) {
                        callback('查无此权限');
                        return;
                    }

                    if (userVipInfo.vip_type != 1 && userVipInfo.vip_type != 2) {//只修改数值类
                        callback('不可扣除');
                        return;
                    }

                    if (data.sign == 0) {//增加

                        if ((data.point + userVipInfo.lvl) > vipInfo.top_lvl) {
                            callback('超过上限');
                            return;
                        }

                    } else {

                        if (userVipInfo.lvl < data.point) {
                            callback('余量不足');
                            return;
                        }

                    }
                    callback(null, userVipInfo);
                });
            },

            //更改 积分／押金
            function (userVipInfo, callback) {
                var endTime = new Date();
                connection.query('UPDATE user_vip SET lvl = ? WHERE uid = ? AND app_sid = ? AND vip_sid = ? AND end_time = ? ', [(userVipInfo.lvl - data.point), data.uid, data.appSid, data.vipSid, endTime], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows > 0) {
                        callback(null, userVipInfo);
                        return;
                    }
                    callback('扣除失败');
                    console.log('更改user_vip表失败')
                    return;

                });
            },

            //记录扣除记录
            function (userVipInfo, callback) {
                if (!userVipInfo) {
                    callback('扣除失败');
                    return;
                }
                var vipLogInfo = {

                    seller_account: 'srv',
                    client_account: userVipInfo.account,
                    vip_name: data.vipName ? data.vipName : 'srv', //查询信用积分时，这项是商品名
                    vip_type: userVipInfo.vip_type,
                    lvl: data.point,
                    duration: '0',
                    cost: 0,
                    exInfo: data.exInfo,
                    comment: data.comment,
                    price: 0,
                    num: 1,
                    app_sid: data.appSid,
                    vip_sid: data.vipSid,
                    original_lvl: userVipInfo.lvl,
                    sign: 1
                };
                connection.query('INSERT INTO vip_log SET ? ', [vipLogInfo], function (err, result) {
                    if (err) {
                        console.log(err);
                        callback(err);
                        return;
                    }
                    if (result.affectedRows <= 0) {
                        callback('操作失败');
                        console.log('更新users表失败')
                        return;
                    }
                    var newLvl = vipLogInfo.original_lvl - vipLogInfo.lvl;
                    callback(null, newLvl); //把最新积分返回回去
                });

            }

        ], function (err, res) {
            if (err) {
                connection.rollback(function () {
                    connection.release();
                    cb(err);
                });
            } else {
                connection.commit(function (e) {
                    if (e) {
                        connection.rollback(function () {
                            connection.release();
                            cb(e);
                        });
                    } else {
                        connection.release();
                        cb(null, res);
                    }
                });
            }
        });

    });

}


//创建用户信用积分vip权限
SrvLink.creditScore = function (data, cb) {

    if (!data) return cb(new Error(500));
    DBFactory.getConnection(function (error, connection) {
        connection.query("SELECT uid FROM user_vip WHERE uid = ? AND app_sid = 'paodan' AND vip_sid = 'credit' ", [data.uid], function (err, result) {
            if (err) {
                cb(err);
                connection.release();
                return;
            }
            var userVipInfo = (result && result.length > 0) ? result[0] : undefined;
            if (userVipInfo) {
                cb('重复操作');
                connection.release();
                return;
            }

            var creditInfo = {
                uid: data.uid,
                account: data.account,
                app_sid: 'paodan',
                vip_sid: 'credit',
                lvl: 100,
                created_time: new Date(),
                end_time: new Date(),
                vip_type: 1
            };
            connection.query("INSERT INTO user_vip set ? ", [creditInfo], function (err, result) {
                if (err) {
                    cb(err);
                    connection.release();
                    return;
                }

                var res = {
                    credit: {
                        vip_sid: creditInfo.vip_sid,
                        vip_name: '信用积分',
                        vip_level: creditInfo.lvl,
                        can_use: 1
                    }
                };
                if (result.affectedRows > 0) {
                    cb(null, res);
                    connection.release();
                    return;
                }
                cb('操作失败');
                connection.release();
            });
        });
    });
}

SrvLink.getAccountWithUid = function (data, cb) {
    if (!data) return cb(new Error(500));
    if (!data.uid) return cb('推荐码不为空');
    DBFactory.poolQuery('SELECT account FROM users WHERE uid = ? ',[data.uid],
        function () {
            cb('no connection');
        },
        function(err, result){
            if(err){
                cb(err);
                console.log(err);
                return;
            }
            var userInfo = (result && result[0]) ? result[0] : undefined;
            cb(null,userInfo);
        }
    );
}